package cn.congine.wizarpos.mall.action;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.congine.wizarpos.mall.common.Page;
import cn.congine.wizarpos.mall.model.ErpProduct;
import cn.congine.wizarpos.mall.model.open.AccessTokenInput;
import cn.congine.wizarpos.mall.model.open.CommonResultOutput;
import cn.congine.wizarpos.mall.model.open.Merchandise;
import cn.congine.wizarpos.mall.model.open.MerchandiseSyncInput;
import cn.congine.wizarpos.mall.model.open.MerchandiseSyncOutput;
import cn.congine.wizarpos.mall.model.open.MerchantDef;
import cn.congine.wizarpos.mall.model.open.MerchantDefQueryInput;
import cn.congine.wizarpos.mall.model.open.MerchantDefQueryOutput;
import cn.congine.wizarpos.mall.model.open.WeChartMemberInfoQueryInput;
import cn.congine.wizarpos.mall.model.open.WeChartMemberInfoQueryOutput;
import cn.congine.wizarpos.mall.service.impl.WizarposOpenRestClient;
import cn.congine.wizarpos.mall.utils.Function;
import cn.congine.wizarpos.mall.utils.SysConstants;
import cn.congine.wizarpos.mall.utils.WxSignUtil;

@Controller
@RequestMapping(value = "/index")
public class IndexAction {
	private static Logger logger = Logger.getLogger(IndexAction.class);
	
	@Autowired
	private WizarposOpenRestClient wizarposOpenRestClient;
	
	@Resource(name = "messageSource")
	private MessageSource messageSource;
	@RequestMapping(value = "/index")
	public ModelAndView index(
			@RequestParam(value = "openId") String openId,
			@RequestParam(value = "mid") String mid,
			@RequestParam(value = "hotJudge", required = false) String hotJudge) {
		
		MerchandiseSyncInput producthotInput = new MerchandiseSyncInput(); 
		producthotInput.setMid(mid);
		producthotInput.setHot(hotJudge);
		MerchandiseSyncOutput producthotOutput = (MerchandiseSyncOutput) wizarposOpenRestClient.post(producthotInput,"/product/merchandise",MerchandiseSyncOutput.class);
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> getpricehot = new HashMap<String, Object>();
		Map<String, Object> getmberpricehot = new HashMap<String, Object>();

		MerchantDefQueryInput merchantDefQueryInput = new MerchantDefQueryInput();
		merchantDefQueryInput.setMid(mid);
		MerchantDefQueryOutput merchantDefQueryOutput = (MerchantDefQueryOutput) wizarposOpenRestClient.post(merchantDefQueryInput,"/merchantdef/info",MerchantDefQueryOutput.class);
		MerchantDef merchantDef = merchantDefQueryOutput.getResult();		
		
		if (StringUtils.isEmpty(merchantDef.getBannerImage()) && !StringUtils.isEmpty(merchantDef.getLogoImage())) {
			merchantDef.setBannerImage(Function.dealGridPicUrl(
					merchantDef.getLogoImage(), 300, 300));
		} else if (StringUtils.isEmpty(merchantDef.getBannerImage()) && StringUtils.isEmpty(merchantDef.getLogoImage())) {
			merchantDef.setBannerImage(SysConstants.DEFAULT_PICTURE_DETAIL);
		}		
	
		List<Merchandise> list = producthotOutput.getResult();
		List<ErpProduct> producthot = new ArrayList<ErpProduct>();

		for (Merchandise merchandise : list) {
			getpricehot.put(merchandise.getProductId(), merchandise.getPrice());
			getmberpricehot.put(merchandise.getProductId(), merchandise.getMemberPrice());
			
			ErpProduct erpProduct = new ErpProduct();
			erpProduct.setShowMemPrice(merchandise.getMemberPrice());
			erpProduct.setId(merchandise.getProductId());
			erpProduct.setName(merchandise.getName());
			
			// 商品图片---多张			
			if ("".equals(merchandise.getPicUrl())) {
				erpProduct.setPicUrl(SysConstants.DEFAULT_PICTURE);
			} else {
				erpProduct.setPicUrl(Function.dealGridPicUrl(merchandise.getPicUrl(), 150, 150));
			}
			// 商品名称过长，做部分截取
			formatProdName(erpProduct);
			producthot.add(erpProduct);
		}

		data.put("merchant", merchantDef);
		data.put("getpricehot", getpricehot);
		data.put("getmberpricehot", getmberpricehot);
		data.put("producthot", producthot);
		data.put("openId", openId);
		data.put("mid", mid);
		return new ModelAndView("index/index", data);
	}	

	@RequestMapping(value = "/toIndex")
	public ModelAndView mystore(@RequestParam(value = "openId") String openId,
			@RequestParam(value = "mid") String mid) {
		Map<String, Object> data = new HashMap<String, Object>();
		WeChartMemberInfoQueryInput input = new WeChartMemberInfoQueryInput();
		input.setMid(mid);
		input.setOpenId(openId);
		WeChartMemberInfoQueryOutput output = (WeChartMemberInfoQueryOutput) wizarposOpenRestClient.post(input, "/wechart/info/query", WeChartMemberInfoQueryOutput.class);

		// 判断当前的微信号是否为此商户的注册会员，		
		if ("60007".equals(output.getCode())) {//会员不存在
			data.put("mid", mid);
			data.put("openId", openId);
			return new ModelAndView("card/receive_card", data);		
		}		

		data.put("openId", openId);
		data.put("mid", mid);
		data.put("cardId", output.getResult().getId());
		return new ModelAndView("index/mystore", data);
	}
	
	@RequestMapping(value = "/get_product")
	@ResponseBody
	public List<ErpProduct> getProduct(
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "hotJudge", required = false) String hotJudge,
			@RequestParam(value = "categoryId", required = false) String categoryId,
			@RequestParam(value = "keyWord", required = false) String keyWord,
			@RequestParam(value = "nextPage", defaultValue = "1") Integer nextPage) {
		MerchandiseSyncInput producthotInput = new MerchandiseSyncInput();
		producthotInput.setMid(mid);
		producthotInput.setCategoryId(categoryId);
		producthotInput.setHot(hotJudge);
		producthotInput.setName(keyWord);
		producthotInput.setPageNo(nextPage.toString());
		MerchandiseSyncOutput producthotOutput = (MerchandiseSyncOutput) wizarposOpenRestClient.post(producthotInput,"/product/merchandise",MerchandiseSyncOutput.class);
		Map<String, Object> getpricehot = new HashMap<String, Object>();
		Map<String, Object> getmberpricehot = new HashMap<String, Object>();
		Page<ErpProduct> page = new Page<ErpProduct>();
		page.setPageNo(nextPage);
		List<Merchandise> list = producthotOutput.getResult();
		List<ErpProduct> producthot = new ArrayList<ErpProduct>();

		for (Merchandise merchandise : list) {
			getpricehot.put(merchandise.getProductId(), merchandise.getPrice());
			getmberpricehot.put(merchandise.getProductId(), merchandise.getMemberPrice());
			
			ErpProduct erpProduct = new ErpProduct();
			erpProduct.setShowMemPrice(merchandise.getMemberPrice());
			erpProduct.setId(merchandise.getProductId());
			erpProduct.setName(merchandise.getName());
			
			// 商品图片---多张			
			if ("".equals(merchandise.getPicUrl())) {
				erpProduct.setPicUrl(SysConstants.DEFAULT_PICTURE);
			} else {
				erpProduct.setPicUrl(Function.dealGridPicUrl(merchandise.getPicUrl(), 150, 150));
			}
			// 商品名称过长，做部分截取
			formatProdName(erpProduct);
			producthot.add(erpProduct);
		}
		return producthot;
	}

	@RequestMapping(value = "/search", method = RequestMethod.GET)
	public ModelAndView search(
			@RequestParam(value = "openId") String openId,
			@RequestParam(value = "mid") String mid,
			@RequestParam(value = "categoryId", required = false) String categoryId,
			@RequestParam(value = "hotJudge", required = false) String hotJudge,
			@RequestParam(value = "keyWord", required = false) String keyWord)
					throws UnsupportedEncodingException {
		
		MerchandiseSyncInput producthotInput = new MerchandiseSyncInput();
		producthotInput.setMid(mid);
		producthotInput.setCategoryId(categoryId);
		producthotInput.setHot(hotJudge);
		if (!"".equals(keyWord)) {
			keyWord = URLDecoder.decode(keyWord, "UTF-8");// 防止中文乱码
		}
		producthotInput.setName(keyWord);
		MerchandiseSyncOutput producthotOutput = (MerchandiseSyncOutput) wizarposOpenRestClient.post(producthotInput,"/product/merchandise",MerchandiseSyncOutput.class);
		
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> getpricehot = new HashMap<String, Object>();
		Map<String, Object> getmberpricehot = new HashMap<String, Object>();
		Map<String, Object> getpriceMhot = new HashMap<String, Object>();
		Map<String, Object> getmberpriceMhot = new HashMap<String, Object>();
		if (!"".equals(keyWord)) {
			keyWord = URLDecoder.decode(keyWord, "UTF-8");// 防止中文乱码
		}
		logger.info("开始搜索产品,catagoryId:" + categoryId + "keyWord:" + keyWord);
		
		List<Merchandise> list = producthotOutput.getResult();
		List<ErpProduct> producthot = new ArrayList<ErpProduct>();

		for (Merchandise merchandise : list) {
			getpricehot.put(merchandise.getProductId(), merchandise.getPrice());
			getmberpricehot.put(merchandise.getProductId(), merchandise.getMemberPrice());
			
			ErpProduct erpProduct = new ErpProduct();
			erpProduct.setShowMemPrice(merchandise.getMemberPrice());
			erpProduct.setId(merchandise.getProductId());
			erpProduct.setName(merchandise.getName());
			
			// 商品图片---多张			
			if ("".equals(merchandise.getPicUrl())) {
				erpProduct.setPicUrl(SysConstants.DEFAULT_PICTURE);
			} else {
				erpProduct.setPicUrl(Function.dealGridPicUrl(merchandise.getPicUrl(), 150, 150));
			}
			// 商品名称过长，做部分截取
			formatProdName(erpProduct);
			producthot.add(erpProduct);
		}
		data.put("getmberpricehot", getmberpricehot);
		data.put("producthot", producthot);
		data.put("openId", openId);
		data.put("categoryId", categoryId);
		data.put("mid", mid);
		data.put("keyWord", keyWord);
		return new ModelAndView("productcategory/prolist", data);
	}

	@RequestMapping(value = "/toSearch", method = RequestMethod.GET)
	public ModelAndView toSearch(
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "categoryId", required = false) String categoryId,
			@RequestParam(value = "hotJudge", required = false) String hotJudge,
			@RequestParam(value = "keyWord", required = false) String keyWord)
			throws UnsupportedEncodingException {
		
		MerchandiseSyncInput producthotInput = new MerchandiseSyncInput();
		producthotInput.setMid(mid);
		producthotInput.setCategoryId(categoryId);
		producthotInput.setHot(hotJudge);
		MerchandiseSyncOutput producthotOutput = (MerchandiseSyncOutput) wizarposOpenRestClient.post(producthotInput,"/product/merchandise",MerchandiseSyncOutput.class);
		
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> getpricehot = new HashMap<String, Object>();
		Map<String, Object> getmberpricehot = new HashMap<String, Object>();

		List<Merchandise> list = producthotOutput.getResult();
		List<ErpProduct> producthot = new ArrayList<ErpProduct>();

		for (Merchandise merchandise : list) {
			getpricehot.put(merchandise.getProductId(), merchandise.getPrice());
			getmberpricehot.put(merchandise.getProductId(), merchandise.getMemberPrice());
			
			ErpProduct erpProduct = new ErpProduct();
			erpProduct.setShowMemPrice(merchandise.getMemberPrice());
			erpProduct.setId(merchandise.getProductId());
			erpProduct.setName(merchandise.getName());
			
			// 商品图片---多张			
			if ("".equals(merchandise.getPicUrl())) {
				erpProduct.setPicUrl(SysConstants.DEFAULT_PICTURE);
			} else {
				erpProduct.setPicUrl(Function.dealGridPicUrl(merchandise.getPicUrl(), 150, 150));
			}
			// 商品名称过长，做部分截取
			formatProdName(erpProduct);
			producthot.add(erpProduct);
		}
		data.put("getpricehot", getpricehot);
		data.put("getmberpricehot", getmberpricehot);
		data.put("producthot", producthot);
		data.put("openId", openId);
		data.put("categoryId", categoryId);
		data.put("mid", mid);
		return new ModelAndView("index/searchPage", data);
	}

	@RequestMapping(value = "/searchAll", method = RequestMethod.GET)
	public ModelAndView searchAll(
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "categoryId", required = false) String categoryId,
			@RequestParam(value = "hotJudge", required = false) String hotJudge,
			@RequestParam(value = "keyWord", required = false) String keyWord,
			Model model) throws UnsupportedEncodingException {
		
		if (StringUtils.isNotEmpty(keyWord)) {
			keyWord = URLDecoder.decode(keyWord, "UTF-8");// 防止中文乱码
		}		
		MerchandiseSyncInput producthotInput = new MerchandiseSyncInput();
		producthotInput.setMid(mid);
		producthotInput.setCategoryId(categoryId);
		producthotInput.setHot(hotJudge);
		producthotInput.setName(keyWord);
		MerchandiseSyncOutput producthotOutput = (MerchandiseSyncOutput) wizarposOpenRestClient.post(producthotInput,"/product/merchandise",MerchandiseSyncOutput.class);
		
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> getpricehot = new HashMap<String, Object>();
		Map<String, Object> getmberpricehot = new HashMap<String, Object>();
		Map<String, Object> getpriceMhot = new HashMap<String, Object>();
		Map<String, Object> getmberpriceMhot = new HashMap<String, Object>();

		logger.info("开始搜索产品," + "keyWord" + keyWord);
		List<Merchandise> list = producthotOutput.getResult();
		List<ErpProduct> producthot = new ArrayList<ErpProduct>();

		for (Merchandise merchandise : list) {
			getpricehot.put(merchandise.getProductId(), merchandise.getPrice());
			getmberpricehot.put(merchandise.getProductId(), merchandise.getMemberPrice());
			
			ErpProduct erpProduct = new ErpProduct();
			erpProduct.setShowMemPrice(merchandise.getMemberPrice());
			erpProduct.setId(merchandise.getProductId());
			erpProduct.setName(merchandise.getName());
			
			// 商品图片---多张			
			if ("".equals(merchandise.getPicUrl())) {
				erpProduct.setPicUrl(SysConstants.DEFAULT_PICTURE);
			} else {
				erpProduct.setPicUrl(Function.dealGridPicUrl(merchandise.getPicUrl(), 150, 150));
			}
			// 商品名称过长，做部分截取
			formatProdName(erpProduct);
			producthot.add(erpProduct);
		}
		data.put("getpricehot", getpricehot);
		data.put("getmberpricehot", getmberpricehot);
		data.put("producthot", producthot);
		data.put("openId", openId);
		data.put("categoryId", categoryId);
		data.put("mid", mid);
		model.addAttribute("keyWord", keyWord);
		return new ModelAndView("index/searchPage", data);
	}

	/**
	 * 商品名称过长，做部分截取
	 * 
	 * @param erpProduct
	 */
	private void formatProdName(ErpProduct erpProduct) {
		String name = erpProduct.getName();
		if (name != null && name.length() > 23) {
			erpProduct.setName(name.substring(0, 20) + "...");
		}
	}
	
	@RequestMapping(value = "/ys", method = RequestMethod.GET)
	public ModelAndView ys(
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			HttpServletRequest httpRequest) throws UnsupportedEncodingException {
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> getpricehot = new HashMap<String, Object>();
		Map<String, Object> getmberpricehot = new HashMap<String, Object>();
		//获取商户信息
		MerchantDefQueryInput merchantDefQueryInput = new MerchantDefQueryInput();
		merchantDefQueryInput.setMid(mid);
		MerchantDefQueryOutput merchantDefQueryOutput = (MerchantDefQueryOutput) wizarposOpenRestClient.post(merchantDefQueryInput,"/merchantdef/info",MerchantDefQueryOutput.class);
		MerchantDef merchant = merchantDefQueryOutput.getResult();
		if (merchant == null) {
			data.put("err_message", "该商户不存在");
			return new ModelAndView("error", data);
		}
		data.put("merchant", merchant);
		data.put("openId", openId);
		data.put("mid", mid);
				
		MerchandiseSyncInput producthotInput = new MerchandiseSyncInput();
		producthotInput.setMid(mid);
		MerchandiseSyncOutput producthotOutput = (MerchandiseSyncOutput) wizarposOpenRestClient.post(producthotInput,"/product/merchandise",MerchandiseSyncOutput.class);
		
		List<Merchandise> list = producthotOutput.getResult();
		List<ErpProduct> producthot = new ArrayList<ErpProduct>();
		for (Merchandise merchandise : list) {
			getpricehot.put(merchandise.getProductId(), merchandise.getPrice());
			getmberpricehot.put(merchandise.getProductId(), merchandise.getMemberPrice());
			
			ErpProduct erpProduct = new ErpProduct();
			erpProduct.setShowMemPrice(merchandise.getMemberPrice());
			erpProduct.setId(merchandise.getProductId());
			erpProduct.setName(merchandise.getName());
			
			// 商品图片---多张			
			if ("".equals(merchandise.getPicUrl())) {
				erpProduct.setPicUrl(SysConstants.DEFAULT_PICTURE);
			} else {
				erpProduct.setPicUrl(Function.dealGridPicUrl(merchandise.getPicUrl(), 150, 150));
			}
			producthot.add(erpProduct);
		}
		data.put("producthot", producthot);
		data.put("getmberpricehot", getmberpricehot);
		
		//请求微信 js api的完整页面地址
		String baseUrl = "http://"
				+ messageSource.getMessage(SysConstants.SERVICE_DNS , null,
						Locale.ENGLISH);
		baseUrl += httpRequest.getSession().getServletContext().getContextPath();
		StringBuffer tmpUrl = new StringBuffer();
		tmpUrl.append(baseUrl);
		tmpUrl.append("/index/ys");
		tmpUrl.append("?openId=").append(openId);
		tmpUrl.append("&mid=").append(mid);
		String url = tmpUrl.toString();
		
		AccessTokenInput jsInput = new AccessTokenInput();
		jsInput.setMid(mid);
		CommonResultOutput jsOutput = (CommonResultOutput) wizarposOpenRestClient.post(jsInput, "/weixin/ticket/js", CommonResultOutput.class);		
		if (jsOutput == null || SysConstants.OPEN_ERROR.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.OPEN_ERROR);
		} else if (SysConstants.NO_MERCHANT_CODE.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.NO_MERCHANT);
		} else {
			Map<String, String> result = (Map<String, String>) jsOutput.getResult();
			String jsTicket = result.get("ticket");
			String appid = result.get("appid");
			data.put("appId", appid);
			Map<String, String> ret = WxSignUtil.commonSign(jsTicket, url,
					WxSignUtil.createTimestamp());
			data.putAll(ret);
		}
		
		return new ModelAndView("ys/ys", data);
	}
}
